﻿using DataAccessLayer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using Xceed.Wpf.Toolkit;
using System.Runtime.ExceptionServices;
using System.Data.SqlClient;

namespace GroepEF4
{
    /// <summary>
    /// Interaction logic for AdminWindow.xaml
    /// </summary>
    public partial class AdminWindow : MetroWindow
    {
        public AdminWindow()
        {
            InitializeComponent();
        }

        private void MetroWindow_Loaded(object sender, RoutedEventArgs e)
        {
            ContractOpkomendGrid.ItemsSource = DataAccessLayer.ContractDB.GetContractsLopend();
            ContractAfgelopenGrid.ItemsSource = DataAccessLayer.ContractDB.GetContractsAfgelopen();
            CompanyGrid.ItemsSource = DataAccessLayer.CompanyDB.ShowAll();
            ContractFormulaGrid.ItemsSource = DataAccessLayer.ContractFormulaDB.GetContractFormulas();
        }



        private void ToggleFlyout(int index)
        {
            var flyout = this.Flyouts.Items[index] as Flyout;
            if (flyout == null)
            {
                return;
            }

            flyout.IsOpen = !flyout.IsOpen;
        }

        private void AddContract_Click(object sender, RoutedEventArgs e)
        {
            cboCompany.ItemsSource = DataAccessLayer.CompanyDB.ShowAll();
            cboFormule.ItemsSource = DataAccessLayer.ContractFormulaDB.GetContractFormulas();
            this.ToggleFlyout(0);

        }

        private async void UpdateContract_Click(object sender, RoutedEventArgs e)
        {
             Contract c = (Contract)ContractOpkomendGrid.SelectedItem;
            if (c == null)
            {
                await this.ShowMessageAsync("Fout!", "Je moet eerst een contract selecteren!");
            }
            else
            {
                cboCompany2.ItemsSource = DataAccessLayer.CompanyDB.ShowAll();
                cboCompany2.SelectedValue = c.CompanyId;
                cboFormula2.ItemsSource = DataAccessLayer.ContractFormulaDB.GetContractFormulas();
                cboFormula2.SelectedValue = c.ContractFormulaId;

                DateBegin2.Value = c.StartDate;
                DateEnd2.Value = c.EndDate;

                this.ToggleFlyout(1);
            }

           
        }

        private void EditContract_Click(object sender, RoutedEventArgs e)
        {

        }

        private void RemoveContract_Click(object sender, RoutedEventArgs e)
        {

        }

        private async void StopContract_Click(object sender, RoutedEventArgs e)
        {
                        var mySettings = new MetroDialogSettings()
            {
                AffirmativeButtonText = "Ja",
                NegativeButtonText = "Nee",
            };

            Contract c = (Contract)ContractOpkomendGrid.SelectedItem;
            if (c == null)
            {
                await this.ShowMessageAsync("Fout!", "Selecteer een opkomend of lopend contract");
            }
            else
            {
                MessageDialogResult result = await this.ShowMessageAsync("Contract stoppen", "Weet je zeker dat je dit contract wil stoppen?",
                MessageDialogStyle.AffirmativeAndNegative, mySettings);


                if (result != MessageDialogResult.Negative)
                {

                    bool ReservationControle = DataAccessLayer.ContractDB.ContractReservationControle(c.CompanyId);

                    if (ReservationControle == true)
                    {
                        int aantal = ContractDB.StopContract(c);
                        await this.ShowMessageAsync("Gestopt", "Het contract is gestopt!");
                        ContractOpkomendGrid.ItemsSource = DataAccessLayer.ContractDB.GetContractsLopend();
                        ContractAfgelopenGrid.ItemsSource = DataAccessLayer.ContractDB.GetContractsAfgelopen();
                    }
                    else
                    {
                        await this.ShowMessageAsync("Fout!", "Het contract kan niet worden gestopt, omdat er nog reservaties zijn voor dit contract!");
                    }
                    
                }

                else
                {
                    await this.ShowMessageAsync("Niet Gestopt!", "Het contract is NIET gestopt!");
                }
        }
        }


        private void DeleteContract_Click(object sender, RoutedEventArgs e)
        {
            this.ToggleFlyout(3);
        }

        private async void DeleteCompany_Click(object sender, RoutedEventArgs e)
        {
            var mySettings = new MetroDialogSettings()
            {
                AffirmativeButtonText = "Ja",
                NegativeButtonText = "Nee",
            };

            try
            {
                Company c = (Company)CompanyGrid.SelectedItem;
                if (c == null)
                {
                    await this.ShowMessageAsync("Fout!", "Je moet eerst een bedrijf selecteren!");
                }
                else
                {
                    MessageDialogResult result = await this.ShowMessageAsync("Bedrijf verwijderen", "Weet je zeker dat je dit bedrijf wil verwijderen?",
                    MessageDialogStyle.AffirmativeAndNegative, mySettings);

                    if (result != MessageDialogResult.Negative)
                    {
                        int aantal = CompanyDB.DeleteCompany(c);
                        await this.ShowMessageAsync("Verwijderd", "Het bedrijf is verwijderd!");
                        CompanyGrid.ItemsSource = DataAccessLayer.CompanyDB.ShowAll();
                    }
                    else
                    {
                        await this.ShowMessageAsync("Niet verwijderd!", "Het bedrijf is NIET verwijderd!");
                    }
                }
            }

            catch (SqlException sqlEx)
            {
                if (sqlEx.Message.IndexOf("FK") != -1)
                {
                    string exception = "Het bedrijf kan niet worden verwijdert, omdat er nog contracten en reservaties aan dit bedrijf gebonden zijn!";
                    MessageBoxException(exception);
                }
                else
                {
                    string exception = sqlEx.Number.ToString();
                    MessageBoxException(exception);
                }
            }
            
            catch (Exception ex)
            {
                string exception = ex.ToString();
                this.MessageBoxException(exception);
            }

        }

        private async void EditCompany_Click(object sender, RoutedEventArgs e)
        {
            Company c = (Company)CompanyGrid.SelectedItem;
            if (c == null)
            {
                await this.ShowMessageAsync("Fout!", "Je moet eerst een bedrijf selecteren!");
            }
            else
            {
                txtCompanyName2.Text = c.Name;
                txtCompanyStreet2.Text = c.Street;
                txtCompanyZipcode2.Text = c.Zipcode.ToString();
                txtCompanyCity2.Text = c.City;
                txtCompanyCountry2.Text = c.Country;
                txtCompanyMail2.Text = c.Email;
                txtCompanyTelephone2.Text = c.Phone;
                txtCompanyEmployees2.Text = c.Employees;

                this.ToggleFlyout(5);
            }
        }

        private void AddCompany_Click(object sender, RoutedEventArgs e)
        {
            this.ToggleFlyout(4);
        }

        private async void AddCompanyButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Company c = new Company();
                c.Name = txtCompanyName.Text;
                c.Street = txtCompanyStreet.Text;
                c.Zipcode = int.Parse(txtCompanyZipcode.Text);
                c.City = txtCompanyCity.Text;
                c.Country = txtCompanyCountry.Text;
                c.Email = txtCompanyMail.Text;
                c.Phone = txtCompanyTelephone.Text;
                c.Employees = txtCompanyEmployees.Text;

                int aantal = CompanyDB.InsertCompany(c);

                if (aantal == 0)
                {
                    await this.ShowMessageAsync("Fout!", "Er is geen Bedrijf toegevoegd.");
                }
                else
                {
                    await this.ShowMessageAsync("Succes!", "Het bedrijf is toegevoegd!");
                }
                txtCompanyName.Text = null;
                txtCompanyCity.Text = null;
                txtCompanyCountry.Text = null;
                txtCompanyEmployees.Text = null;
                txtCompanyMail.Text = null;
                txtCompanyStreet.Text = null;
                txtCompanyTelephone.Text = null;
                txtCompanyZipcode.Text = null;
                this.ToggleFlyout(4);
                CompanyGrid.ItemsSource = DataAccessLayer.CompanyDB.ShowAll();
            }
            catch (FormatException ex)
            {
                string exception = "Zipcode en/of telefoonnummer mag geen letters bevatten";
                MessageBoxException(exception);
            }
            catch (InvalidOperationException ex)
            {
                string exception = "Gelieve alle velden in te vullen!";
                MessageBoxException(exception);
            }

            catch (SqlException sqlEx)
            {
                if (sqlEx.Message.IndexOf("CK_Phone") != -1)
                {
                    string exception = "Het telefoonnummer moet 10 cijfers bevatten!";
                    MessageBoxException(exception);
                }
                else if (sqlEx.Message.IndexOf("CK_email") != -1)
                {
                    string exception = "Ongeldig emailadres!";
                    MessageBoxException(exception);
                }
                else
                {
                    string exception = sqlEx.Message.ToString();
                    MessageBoxException(exception);
                }               
            }            
            catch (Exception ex)
            {
                string exception = ex.ToString();
                MessageBoxException(exception);
            }             
        }

        private async void AddContractButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Contract c = new Contract();
                string CompanyName = ((Company)cboCompany.SelectedItem).Name;
                c.CompanyId = DataAccessLayer.CompanyDB.GetCompanyIdByName(CompanyName);

                string FormulaName = ((ContractFormula)cboFormule.SelectedItem).Description;
                c.ContractFormulaId = DataAccessLayer.ContractFormulaDB.GetContractFormulaIdByName(FormulaName);

                c.StartDate = DateBegin.Value.Value;
                c.EndDate = DateEnd.Value.Value;

                bool ContractControle = ContractDB.ContractControle(c.CompanyId, c.StartDate, c.EndDate);

                if(ContractControle == false)
                {
                    await this.ShowMessageAsync("Fout!", "Het contract kan niet worden toegevoegd wegens overlapping van een ander contract");
                }
                else
                {
                    int aantal = ContractDB.InsertContract(c);
                    // if aantal 0 dan doet die niks


                    if (aantal == 0)
                    {
                        await this.ShowMessageAsync("Fout!", "Er is geen contract toegevoegd");
                    }
                    else
                    {
                        await this.ShowMessageAsync("Succes!", "Het contract is succesvol toegevoegd");
                    }

                    ContractOpkomendGrid.ItemsSource = DataAccessLayer.ContractDB.GetContractsLopend();
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        private async void UpdateContractButton_Click(object sender, RoutedEventArgs e)
        {
            try { 
                Contract c = (Contract)ContractOpkomendGrid.SelectedItem;
                if (c == null)
                {
                    await this.ShowMessageAsync("Fout!", "Je moet eerst een contract selecteren");
                }
                else
                {
                    string CompanyName = ((Company)cboCompany2.SelectedItem).Name;
                    c.CompanyId = DataAccessLayer.CompanyDB.GetCompanyIdByName(CompanyName);

                    string FormulaName = ((ContractFormula)cboFormula2.SelectedItem).Description;
                    c.ContractFormulaId = DataAccessLayer.ContractFormulaDB.GetContractFormulaIdByName(FormulaName);
                    c.StartDate = DateBegin2.Value.Value;
                    c.EndDate = DateEnd2.Value.Value;

                    int aantal = ContractDB.UpdateContract(c);
                    // if aantal 0 dan doet die niks


                    if (aantal == 0)
                    {
                        await this.ShowMessageAsync("Fout!", "Er is geen contract toegevoegd");
                    }
                    else
                    {
                        await this.ShowMessageAsync("Succes!", "Het contract is succesvol aangepast");
                    }

                    ContractOpkomendGrid.ItemsSource = DataAccessLayer.ContractDB.GetContractsLopend();
                }
                }
                catch(Exception ex)
                {
                    string exception = ex.ToString();
                    this.MessageBoxException(exception);
                }
            
        }

        private void StopContractButton_Click(object sender, RoutedEventArgs e)
        {

        }
        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
           
                
        }
        private async void UpdateCompanyButton_Click(object sender, RoutedEventArgs e)
        {
                 try { 
                Company c = (Company)CompanyGrid.SelectedItem;
                if (c == null)
                {
                    await this.ShowMessageAsync("Fout!", "Je moet eerst een bedrijf selecteren");
                }
                else
                {
                    c.Name = txtCompanyName2.Text;
                    c.Street = txtCompanyStreet2.Text;
                    c.Zipcode = int.Parse(txtCompanyZipcode2.Text);
                    c.City = txtCompanyCity2.Text;
                    c.Country = txtCompanyCountry2.Text;
                    c.Email = txtCompanyMail2.Text;
                    c.Phone = txtCompanyTelephone2.Text;
                    c.Employees = txtCompanyEmployees2.Text;

                    int aantal = CompanyDB.UpdateCompany(c);
                    // if aantal 0 dan doet die niks


                    if (aantal == 0)
                    {
                        await this.ShowMessageAsync("Fout!", "Er is geen bedrijf toegevoegd");
                    }
                    else
                    {
                        await this.ShowMessageAsync("Succes!", "Het bedrijf is succesvol aangepast");
                    }

                    CompanyGrid.ItemsSource = DataAccessLayer.CompanyDB.ShowAll();
                }
                }
                catch(Exception ex)
                {
                    string exception = ex.ToString();
                    this.MessageBoxException(exception);
                }
            

        }


        private async void DeleteContractButton_Click(object sender, RoutedEventArgs e)
        {
            var mySettings = new MetroDialogSettings()
            {
                AffirmativeButtonText = "Ja",
                NegativeButtonText = "Nee",
            };
           
            
            Contract c = (Contract)ContractOpkomendGrid.SelectedItem;
            if (c == null)
            {
                Contract c2 = (Contract)ContractAfgelopenGrid.SelectedItem;
                if (c2 == null)
                {
                    await this.ShowMessageAsync("Fout!", "Je moet eerst een contract selecteren!");
                }
                else
                {
                    MessageDialogResult result = await this.ShowMessageAsync("Contract verwijderen", "Weet je zeker dat je dit contract wil verwijderen?",
                    MessageDialogStyle.AffirmativeAndNegative, mySettings);

                    if (result != MessageDialogResult.Negative)
                    {
                        int aantal = ContractDB.DeleteContract(c2);
                        await this.ShowMessageAsync("Verwijderd", "Het contract is verwijderd!");
                        ContractAfgelopenGrid.ItemsSource = DataAccessLayer.ContractDB.GetContractsAfgelopen();
                    }
                    else
                    {
                        await this.ShowMessageAsync("Niet verwijderd!", "Het contract is NIET verwijderd!");
                    }
                }              
            }
            else
            {
                MessageDialogResult result = await this.ShowMessageAsync("Contract verwijderen", "Weet je zeker dat je dit contract wil verwijderen?",
                MessageDialogStyle.AffirmativeAndNegative, mySettings);

                if (result != MessageDialogResult.Negative)
                {
                    int aantal = ContractDB.DeleteContract(c);
                    await this.ShowMessageAsync("Verwijderd", "Het contract is verwijderd!");
                    ContractOpkomendGrid.ItemsSource = DataAccessLayer.ContractDB.GetContractsLopend();
                }

                else
                {
                    await this.ShowMessageAsync("Niet verwijderd!", "Het contract is NIET verwijderd!");
                }
            }

            }
      
        private async void MessageBoxException(string ex)
        {
           await this.ShowMessageAsync("Fout!", ex);
        }

        private void LogOutButton_Click(object sender, RoutedEventArgs e)
        {
            MainWindow m = new MainWindow();
            this.Close();
            m.Show();
        }

        private async void CalenderReservation_SelectedDatesChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                String date = CalenderReservation.SelectedDate.ToString();
                CalenderGridAdmin.ItemsSource = DataAccessLayer.ReservationDB.GetReservationsDate(date);

                if (CalenderGridAdmin.Items.Count == 0)
                {
                    await this.ShowMessageAsync("Geen reservaties!", "op de geselecteerde datum zijn nog geen reservaties beschibaar.");
                }
            }
            catch (Exception ex)
            {
                string exception = "Je moet eerst een datum selecteren!";
                MessageBoxException(exception);
            }
        }

        private void DateBegin_ValueChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {          
            DateTime? BeginDate = DateBegin.Value.Value;
            if (!BeginDate.HasValue)
            {
                DateEnd.Value = null;
            }
            else
            {
                int Months = ((ContractFormula)cboFormule.SelectedItem).PeriodInMonths;
                DateTime BeginDate2 = DateBegin.Value.Value;
                DateTime EndDate = BeginDate2.AddMonths(Months);
                DateEnd.Value = EndDate;
            }
            
        }            
        }    
    }